Ext.define('BISC.view.Viewport', {
  extend: 'BISC.view.MyViewport',
  renderTo: Ext.getBody(),
  requires: [
    'BISC.view.MyViewport',
    'BISC.view.FolderManagerWindow',
    'BISC.view.AttributeWindow'
  ]
});

Ext.onReady( function() {
    Ext.data.Connection.prototype.useDefaultXhrHeader = false;

    var mask = new Ext.LoadMask( Ext.getBody(), { autoShow: true, msg: 'Loading...' } );

    // set app and server settings to a global
    Ext.data.JsonP.request({
        url: 'http://localhost:8888/getSettings',
        callback: function( success, res ) {
            if ( res.success ) {
                Config = res.data;
                if ( Config.server ) {
                    // synchronize monitors and images
                    Ext.data.JsonP.request({
                        url: 'http://localhost:8888/startup',
                        callback: function( success, res ) {
                            if ( res && res.success ) {
                                console.log( 'Monitors and images successfully synchronized!' );
                                // load images
                                imagePanel = Ext.getCmp( 'ImagesPanel' );
                                if ( imagePanel ) imagePanel.filterBy();
                            } else {
                                console.log( 'Monitors and images synchronization failed!' );
                            }
                        }
                    });

                    // update any element that shows the server name
                    Ext.select('.serverName').update( Config.server.name );

                    // synchronize categories and attributes
                    Ext.data.JsonP.request({
                        url: 'http://localhost:8888/updateCache?bisId=' + Config.server.id,
                        callback: function( st, data ) {
                            mask.hide();
                            if ( data && data.success ) {
                                console.log( 'Categories and attributes successfully synchronized!' );
                                Ext.getCmp('categoryTreePanel').getStore().getProxy().extraParams = {
                                    bisId: Config.server.id
                                };
                                Ext.getCmp('categoryTreePanel').getStore().load();
                            } else {
                                console.log( 'Categories and attributes synchronization failed!' );
                            }
                        }
                    });
                } else {
                    mask.hide();
                    Ext.Msg.alert( 'No configuration found!', 'Please select Tools > Settings from the menu above and configure a server, then restart the software.' );
                }
            } else {
                mask.hide();
                Ext.Msg.alert( 'Server not connected!', 'Please restart the software.' );
            }
        }
    });

});

socket = io.connect('http://localhost');
socket.on('imageAdded', function( data ) {
    var store = Ext.StoreManager.lookup('ImagesStore');
    store.add( data.data.image );
    store = Ext.StoreManager.lookup('FolderListStore');
    var monitor = store.find( 'id', data.data.image.folderId );
    if ( monitor > -1 ) {
        monitor = store.getAt( monitor );
        monitor.set( 'sz', monitor.get('sz') + 1 );
    }
});
socket.on('imageRemoved', function( data ) {
    var store = Ext.StoreManager.lookup('ImagesStore');
    var image = store.find( 'id', data.data.image.id );
    if ( image > -1 ) store.removeAt( image );

    store = Ext.StoreManager.lookup('FolderListStore');
    var monitor = store.find( 'id', data.data.image.folderId );
    if ( monitor > -1 ) {
        monitor = store.getAt( monitor );
        monitor.set( 'sz', monitor.get('sz') - 1 );
    }
});
socket.on('updateImageProperties', function( data ) {
    if ( Ext.getCmp('propertiesView').image.id == data.data.imageId ) {
        Ext.getCmp('propertiesView').update( data.data.data );
    }
});
socket.on('updateImageThumbnail', function( data ) {
    var store = Ext.StoreManager.lookup('ImagesStore');
    var index = store.findExact('id', data.data.imageId);
    if ( index > -1 ) {
        // record is being displayed
        // just update image.. the rest of the data should be updated by other events or on a full reload
        store.getAt( index ).set('thumbnail', data.data.thumb);
    }
    // otherwise, no need to update
});
socket.on('updateImageUploadedStatus', function( data ) {
    var store = Ext.StoreManager.lookup('ImagesStore');
    var index = store.findExact( 'id', Number(data.data.imageId) );
    if ( index > -1 ) {
        // record is being displayed
        // just update image.. the rest of the data should be updated by other events or on a full reload
        store.getAt( index ).set('online', data.data.online);
    }
    // otherwise, no need to update
});
socket.on('updateCategoryAttributes', function( data ) {
    var store = Ext.StoreManager.lookup('CategoryTreeStore');
    var node = store.getRootNode().findChild( 'categoryId', Number(data.data.categoryId), true );
    if ( node ) {
        Ext.getCmp('categoryTreePanel').getStore().load({
            node: node
        });
    }
    // otherwise, no need to update
});
lastMessage = new Date();
socket.on('updateStatus', function( data ) {
    Ext.getCmp('statusLabel').update( data.data.message );
    lastMessage = new Date();
    var time = lastMessage;
    Ext.defer( function( time ) { if ( lastMessage == time ) Ext.getCmp('statusLabel').update('') }, 5000, this, [ time ] );
});
